package com.quanyan.club.service.impl;

import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.admin.*;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.admin.ReqActivityOrderQuery;
import com.quanyan.club.entity.vo.resp.ClubMemberAccountStreamInfo;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubActivityMember;
import com.quanyan.club.entity.vo.resp.admin.ResActivityOrderVo;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.*;
import com.quanyan.club.util.NumberGenerator;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.vo.resp.RespCity;
import com.quanyan.orderpay.request.ReqOrderCancel;
import com.quanyan.orderpay.request.ReqOrderRefund;
import com.quanyan.orderpay.request.ReqRefundPayInfo;
import com.quanyan.orderpay.request.ReqRefundProduct;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.search.service.ActivitySearchService;
import com.quanyan.search.service.impl.ActivitySearchServiceImpl;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yue.yuan on 2016/8/18.
 */
@Service("clubActivityAdminService")
public class ClubActivityAdminServiceImpl extends BaseServiceImpl implements ClubActivityAdminService {

    private static final Logger logger = LoggerFactory.getLogger(ClubActivityAdminServiceImpl.class);

    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private ClubActivityAdminMapper clubActivityAdminMapper;
    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;
    @Autowired
    private TbActivityPosterMapper tbActivityPosterMapper;
    @Autowired
    private TbClubMapper tbClubMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private ClubAccountService clubAccountService;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private TbOrderRefundMapper orderRefundMapper;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private ClubFinanceMgmService clubFinanceMgmService;
    @Autowired
    private TbClubOnlineMemberAccountStreamMapper clubOnlineMemberAccountStreamMapper;
    @Autowired
    private TbClubActivityAdminOperationMapper clubActivityAdminOperationMapper;
    @Autowired
    private TbClubOnlineMemberAccountMapper clubOnlineMemberAccountMapper;
    @Autowired
    private TbCategoryMapper categoryMapperMapper;
    @Value("${search.cloud.url}")
    public String searchCloudUrl;
    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private PlaceClient placeClient;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private ActivityAccountService activityAccountService;

    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse cancelNotPayActivityOrder(Integer adminId, Integer uid, Integer activityId,
                                                 String businessOrderNo) {
        TbOrderExample tbOrderExample = new TbOrderExample();
        tbOrderExample.createCriteria()
                .andOrderUidEqualTo(uid).andActivityIdEqualTo(activityId)
                .andOrderNoEqualTo(businessOrderNo);
        List<TbOrder> tbOrders = orderMapper.selectByExample(tbOrderExample);

        if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbOrders)) {
            return APIResponse.returnFail("订单不存在");
        }

        TbOrder tbOrder = tbOrders.get(0);
        if (tbOrder.getOrderStatus().intValue() != 1) {
            return APIResponse.returnFail("不能取消订单");
        }

        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(tbOrder.getActivityId()) //活动id
                .andStatusEqualTo((int) Constants.BYTE_ONE)          //有效的
                .andOrderIdEqualTo(tbOrder.getId());
        List<TbSignUser> signUsers = signUserMapper.selectByExample(signUserExample);

        if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(signUsers)) {
            return APIResponse.returnFail("订单不存在");
        }

        APIResponse<RespClubActivity> activityAPIResponse =
                clubActivityService.queryClubActivityById(tbOrder.getActivityId());
        if (!activityAPIResponse.isRet()) {
            return activityAPIResponse;
        }

        //调用支付系统取消未支付订单
        APIRequest<ReqOrderCancel> apiRequest = new APIRequest<ReqOrderCancel>();
        ReqOrderCancel reqOrderCancel = new ReqOrderCancel();
        reqOrderCancel.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        reqOrderCancel.setSourceBusinessId(
                Constants.CLUB_ACTIVITY_ORDER_BUSINESS_CODE);
        reqOrderCancel.setOrderNo(tbOrder.getOrderTradeNo());
        reqOrderCancel.setOutTradeNo(tbOrder.getOrderNo());
        reqOrderCancel.setUid(tbOrder.getOrderUid());
        reqOrderCancel.setCancelReason("订单超时未支付");
        apiRequest.setData(reqOrderCancel);
        APIResponse<BaseEnum> apiResponse = orderPayService.orderCancel(apiRequest);
        if (!apiResponse.isRet()) {
            return apiResponse;
        }

        //恢复报名人数库存
        //计算要取消的男女报名人数
        int manCount = 0, femaleCount = 0;
        for (TbSignUser signUser : signUsers) {
            if (signUser.getGender() == Constants.BYTE_ONE) {
                manCount++;
            }
            if (signUser.getGender() == Constants.BYTE_TWO) {
                femaleCount++;
            }
        }
        logger.warn("count = " + signUsers.size());
        RespClubActivity respClubActivity = activityAPIResponse.getData();
        APIResponse recoveryRes = clubActivityService.recoverySignUpNum(
                respClubActivity.getLimitNum(), tbOrder.getActivityId(), signUsers.size(), femaleCount, 0);
        logger.warn("3 恢复报名人数库存，男：" + signUsers.size() + ", 女：" + femaleCount + ", 返回：" + JSON.toJSONString(recoveryRes));
        if (!recoveryRes.isRet()) {
            return recoveryRes;
        }

        //4. 更新报名人报名记录表
        signUserExample.clear();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andOrderIdEqualTo(tbOrder.getId());
        TbSignUser updateSignUser = new TbSignUser();
        updateSignUser.setIsCancel(1);//取消
        updateSignUser.setStatus(-1);//这里设置为下单超时未支付状态,现场管理成员列表中会去过滤掉超时未支付的.
        int uret = signUserMapper.updateByExampleSelective(updateSignUser, signUserExample);
        logger.warn("4 更新报名人报名记录表，更新为{}，返回：{}", JSON.toJSON(updateSignUser), uret);

        //如果有俱乐部余额抵扣 , 则退回
        if (tbOrder.getBalanceAmount() != null
                && tbOrder.getBalanceAmount().doubleValue() > 0) {
            ClubMemberAccountStreamInfo clubMemberAccountStreamInfo =
                    clubAccountService.addOrDeductionPersonClubAccountBalance(tbOrder.getBalanceAmount(),
                            tbOrder.getOrderUid(), respClubActivity.getClubId(), true);

            if (clubMemberAccountStreamInfo == null) {
                return APIResponse.returnFail("增加账户余额失败");
            }

            //type收支类型：0为充值，1为消费、2为退款
            TbClubOnlineMemberAccountStream tbClubOnlineMemberAccountStream
                    = clubAccountService.getPersonClubAccountStream(
                    tbOrder.getOrderUid(), respClubActivity.getClubId(),
                    respClubActivity.getActivityId(), 1);
            if (tbClubOnlineMemberAccountStream != null) {
                clubAccountService.deletePersonClubAccountStream(
                        tbClubOnlineMemberAccountStream.getId());
            }

            //记录个人账户流水
            //status 0:待处理 1：处理成功 2处理中 3：处理失败
            clubAccountService.recordPersonClubAccountDeductibleStream(
                    tbOrder.getOrderUid(),
                    tbOrder.getActivityId(),
                    respClubActivity.getName() + "报名费退款",
                    tbOrder.getPayType(), respClubActivity.getClubId(),
                    clubMemberAccountStreamInfo,
                    tbOrder.getOrderTradeNo(), (byte) 2, (byte) 2);
        }

        tbOrder.setCancelType((byte) 5);
        tbOrder.setOrderStatus((byte) 8);//设置成已取消
        orderMapper.updateByPrimaryKeySelective(tbOrder);

        //记录操作的管理员
        TbClubActivityAdminOperation clubActivityAdminOperation = new TbClubActivityAdminOperation();
        clubActivityAdminOperation.setActivityId(activityId);
        clubActivityAdminOperation.setAdminId(adminId);
        clubActivityAdminOperation.setUserId(uid);
        clubActivityAdminOperation.setBusinessOrderNo(businessOrderNo);
        clubActivityAdminOperation.setOperationType((byte) 1);
        clubActivityAdminOperation.setCreateTime(new Date());
        clubActivityAdminOperation.setUpdateTime(new Date());
        int i = clubActivityAdminOperationMapper.insertSelective(clubActivityAdminOperation);
        if (i <= 0) {
            return APIResponse.returnFail("记录操作的管理员失败");
        }

        return APIResponse.returnSuccess();
    }

    /**
     * 管理员操作退款，通知支付系统退款
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse refundOrderNotify(Integer adminId, Integer uid, String businessOrderNo, Integer cancelType, String reason) {
        //1. 查询订单信息
        TbOrderExample orderExample = new TbOrderExample();
        orderExample.createCriteria().andOrderNoEqualTo(businessOrderNo);
        List<TbOrder> orders = orderMapper.selectByExample(orderExample);
        if (orders == null || orders.size() <= 0) {
            return APIResponse.returnFail("订单不存在");
        }
        TbOrder order = orders.get(0);

        updateSignUpUser(order);        //更新报名状态

        //2. 判断是否可以取消此订单
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria()
                .andActivityIdEqualTo(order.getActivityId()).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(clubActivityExample);
        if (clubActivities == null || clubActivities.size() <= 0) {
            throw new BizException("俱乐部活动不存在");
        }
        TbClubActivity clubActivity = clubActivities.get(0);
        if (clubActivity.getIsCancelSignUp() == Constants.IS_YES) {
            throw new BizException("不可取消报名");   //不可取消报名
        }
        if (clubActivity.getIsSettle() == Constants.IS_YES) {
            throw new BizException("活动已经结算");   //活动已经结算
        }
        ActivityInfo activityInfo = activityOpenService.selectOneActivityById(clubActivity.getActivityId());
        /*Date activityStartTime = activityInfo.getStartTime(); //活动开始时间
        Byte limitTime = clubActivity.getCancelTimeLimit();   //活动开始前，可取消限制时间，单位：小时
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(activityStartTime);
        calendar.add(Calendar.HOUR_OF_DAY, -1 * limitTime);
        if (!(new Date().before(calendar.getTime()))) {     //当前时间不在可取消的时间范围内
            throw new BizException("当前时间不在可取消的时间范围内");
        }*/

        String refundOrderNo = CommonUtils.generateOrderNo(uid);//退款单号

        //3. 退款
        //记录退款痕迹
        //取消类型 '0 未取消,  取消对象: 1 用户主动取消已支付订单(退款) 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消 5用户取消未支付订单',
        byte refundType = -1;
        if (cancelType == 1) {
            refundType = 2;
        }
        if (cancelType == 3) {
            refundType = 6;
        }
        if (cancelType == 4) {
            refundType = 4;
        }

        //1: 活动结算AA退款 2:用户取消已支付订单退款 3:活动发起人取消已支付订单退款 4:活动未达到开启条件,给已经报名支付成功的人退款 5现场管理人补请假退款
        this.insertOrderRefund(
                order.getPayAmount(),
                order.getId(),
                order.getPayType(),
                order.getOrderUid(), reason,
                refundType, refundOrderNo);
        logger.warn("订单：" + order.getOrderNo() + ", 退款：第三方支付" + order.getPayAmount().doubleValue() + ", 俱乐部余额抵扣" + order.getBalanceAmount().doubleValue() + ", 鸟蛋抵扣" + order.getAccumulateAmount());
        //3.1 没有第三方支付和鸟蛋支付，不调支付系统退款，直接退俱乐部抵扣余额
        if (order.getPayAmount().doubleValue() == 0
                && order.getAccumulateAmount() == 0) {
            logger.warn("没有第三方支付和鸟蛋支付，不调支付系统退款，直接退俱乐部抵扣余额");
            //4. 更新订单状态
            order.setOrderStatus((byte) 4); //退款中
            order.setCancelType(cancelType.byteValue()); //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消
            orderMapper.updateByPrimaryKeySelective(order);

            boolean isret = clubActivityService.cancelOrderNotifyCallbackAdmin(order.getOrderNo());
            if (!isret) {
                logger.warn("直接退俱乐部抵扣余额，失败");
                throw new BizException("直接退俱乐部抵扣余额，失败");
            }

            //4. 更新订单状态
            order.setOrderStatus((byte) 5); //退款完成
            order.setCancelType(cancelType.byteValue()); //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消
            orderMapper.updateByPrimaryKeySelective(order);
        } else {
            //3.2 调用支付系统，申请退款
            APIRequest<ReqOrderRefund> refundRequest = new APIRequest<>();
            ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
            reqOrderRefund.setNeedAudit(false);     //无需审核
            reqOrderRefund.setUid(uid);             //申请退款人uid
            reqOrderRefund.setSourceBusinessId(Constants.CLUB_ACTIVITY_ORDER_BUSINESS_CODE);   //业务id
            reqOrderRefund.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
            reqOrderRefund.setOrderNo(order.getOrderTradeNo());             //订单系统订单号
            reqOrderRefund.setOutTradeNo(order.getOrderNo());               //业务系统订单号
            reqOrderRefund.setOutTradeRefundNo(refundOrderNo);         //退款订单号，目前为活动的订单号
            reqOrderRefund.setAmount(order.getOrderAmount());
            if (reason != null) {
                reqOrderRefund.setReason(reason);
            } else {
                reqOrderRefund.setReason(order.getInfo());  //取消原因
            }
            List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<>();

            if (order.getPayAmount().doubleValue() != 0) {
                ReqRefundPayInfo rmb = new ReqRefundPayInfo();
                int type = order.getPayType();
                switch (type) {
                    case ClubConstants.PAY_TYPE_ALIPAY:
                        rmb.setPayId(PayWayEnum.PAY_WAY_ALIPAY.getPayId());
                        break;
                    case ClubConstants.PAY_TYPE_WEICHAT:
                        rmb.setPayId(PayWayEnum.PAY_WAY_WEICHAT.getPayId());
                        break;
                    case ClubConstants.PAY_TYPE_WAY_WEICHATH5:
                        rmb.setPayId(PayWayEnum.PAY_WAY_WEICHATH5.getPayId());
                        break;
                    case ClubConstants.PAY_TYPE_APPLYPAY:
                        rmb.setPayId(PayWayEnum.PAY_WAY_APPLE_PAY.getPayId());
                        break;
                    case ClubConstants.PAY_TYPE_UNIONPAY:
                        rmb.setPayId(PayWayEnum.PAY_WAY_UNION_PAY.getPayId());
                        break;
                }
                rmb.setRefundAmount(order.getPayAmount());     //退回应支付费用
                reqRefundPayInfoList.add(rmb);
            }

            if (order.getAccumulateAmount() > 0) {        //如果鸟蛋为0，或小数，支付系统不予退回。
                ReqRefundPayInfo ages = new ReqRefundPayInfo();
                ages.setPayId(PayWayEnum.PAY_WAY_FOR_AGES.getPayId());
                ages.setRefundAmount(new BigDecimal(order.getAccumulateAmount())); //退回抵扣的鸟蛋数
                reqRefundPayInfoList.add(ages);
            }
            reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);

            List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
            ReqRefundProduct refundProduct = new ReqRefundProduct();
            refundProduct.setPrice(order.getOrderAmount());
            refundProduct.setProductId(String.valueOf(order.getActivityId()));
            refundProduct.setQuantity(1);
            refundProduct.setProductName("");
            reqRefundProducts.add(refundProduct);
            reqOrderRefund.setRefundProductList(reqRefundProducts);

            refundRequest.setData(reqOrderRefund);
            APIResponse<RefundStatusEnum> response = orderPayService.refundApply(refundRequest);
            logger.warn("调用支付系统退款，返回：" + JSON.toJSON(response));
            if (!response.isRet()) {
                throw new BizException("调用支付系统退款失败！");       //退款失败
            }

            //4. 更新订单状态
            order.setOrderStatus((byte) 4); //退款中
            order.setCancelType(cancelType.byteValue()); //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消
            orderMapper.updateByPrimaryKeySelective(order);
        }
        Integer activityId = order.getActivityId();

        //3. 恢复报名人数库存
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(activityId) //活动id
                .andOrderIdEqualTo(order.getId())
                .andStatusEqualTo((int) Constants.BYTE_ONE);        //有效的
        List<TbSignUser> signUsers = signUserMapper.selectByExample(signUserExample);
        logger.warn("取消人数：" + JSON.toJSONString(signUsers));
        //计算要取消的男女报名人数
        int manCount = 0, femaleCount = 0;
        for (TbSignUser signUser : signUsers) {
            if (signUser.getGender() == Constants.BYTE_ONE) {
                manCount++;
            }
            if (signUser.getGender() == Constants.BYTE_TWO) {
                femaleCount++;
            }
        }

        logger.warn("更新活动已报名人数，activityId:" + activityId);
        Map<String, Object> paraMap = Maps.newHashMap();
        //更新活动已经报名的有效人数
        try {
            signUserExample.clear();
            signUserExample.createCriteria()
                    .andActivityIdEqualTo(activityId) //活动id
                    .andOrderIdEqualTo(order.getId())
                    .andStatusEqualTo((int) Constants.BYTE_ZERO);        //有效的
            List<TbSignUser> counts = signUserMapper.selectByExample(signUserExample);
            paraMap.put("activityId", activityId);
            int minusCount = (0 - counts.size());
            if (minusCount > 0) {
                minusCount = 0;
            }
            //从活动报名人数库存中减去取消的男女人数
            APIResponse recoveryRes = clubActivityService.recoverySignUpNum(
                    activityInfo.getLimitNum(), order.getActivityId(), counts.size(), femaleCount, 4); //取消
            logger.warn("3 恢复报名人数库存，男：" + counts.size() + ", 女：" + femaleCount + ", 返回：" + JSON.toJSONString(recoveryRes));
            if (!recoveryRes.isRet()) {
                throw new BizException("恢复报名人库存异常：" + JSON.toJSONString(recoveryRes));
            }
            logger.warn("更新报名人数完成, minusCount" + minusCount);
        } catch (RpcException rpe) {
            throw new BizException("调用活动模块失败" + JSON.toJSONString(paraMap));
        }
        //4. 更新报名人报名记录表
        signUserExample.clear();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andOrderIdEqualTo(order.getId());
        TbSignUser updateSignUser = new TbSignUser();
        updateSignUser.setManageType((int) Constants.BYTE_ONE);      //请假（用户取消）
        updateSignUser.setIsCancel((int) Constants.BYTE_ONE);        //取消
        updateSignUser.setStatus(Constants.ZERO);                   //0 无效(is_cancel为取消状态时)
        int uret = signUserMapper.updateByExampleSelective(updateSignUser, signUserExample);
        logger.warn("4 更新报名人报名记录表，更新为{}，返回：{}", JSON.toJSON(updateSignUser), uret);
        if (uret < 0) {
            throw new BizException(" 更新报名人报名记录表失败！");
        }
        //记录操作的管理员
        TbClubActivityAdminOperation clubActivityAdminOperation = new TbClubActivityAdminOperation();
        clubActivityAdminOperation.setActivityId(order.getActivityId());
        clubActivityAdminOperation.setAdminId(adminId);
        clubActivityAdminOperation.setUserId(uid);
        clubActivityAdminOperation.setBusinessOrderNo(businessOrderNo);
        clubActivityAdminOperation.setOperationType((byte) 2);
        clubActivityAdminOperation.setCreateTime(new Date());
        clubActivityAdminOperation.setUpdateTime(new Date());
        int i = clubActivityAdminOperationMapper.insertSelective(clubActivityAdminOperation);
        if (i <= 0) {
            return APIResponse.returnFail("记录操作的管理员失败");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 用户取消订单，更改此用户和他代报名的用户报名记录状态
     */
    private void updateSignUpUser(TbOrder order) {
        TbSignUserExample example = new TbSignUserExample();
        example.createCriteria()
                .andOrderIdEqualTo(order.getId())
                .andActivityIdEqualTo(order.getActivityId());
        TbSignUser signUser = new TbSignUser();
        signUser.setIsCancel(1);    //报名取消
        signUser.setStatus(0);      //状态:  -1 下单超时未支付 0 无效(is_cancel为取消状态时,只有支付成功的订单被取消才会有此状态) 1 有效
        signUserMapper.updateByExampleSelective(signUser, example);
    }

    //根据条件查询活动列表（activityType活动类型,categoryId活动项目,cityId城市,activityStatus活动所有状态，关键词）
    // 已活动报名人数高低筛选条件，距离活动开始倒计时筛选
    //返回（activityName,cityId,activityType活动类型,categoryId活动项目）
    public PageObj<List<ClubActivityListDo>>   queryClubActivityList(ReqClubActivityAdmin req) {
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        Date startQueryTime=req.getStartTime();
        if (startQueryTime != null){
            logger.warn("startQueryTime=" + sf.format(startQueryTime));
            req.setStartTime(startQueryTime);
        }
        Date endQueryTime = getEndQueryTime(startQueryTime,req.getEndTime());
        if (endQueryTime != null){
            logger.warn("endQueryTime=" + sf.format(endQueryTime));
            req.setEndTime(endQueryTime);
        }
        Integer total = clubActivityAdminMapper.countClubActivityList(req);
        Limit limit = Limit.buildLimit(pageNum + 1, pageSize);
        req.setLimit(limit);
        List<ClubActivityListDo> list =
                clubActivityAdminMapper.queryClubActivityList(req);
        for (ClubActivityListDo c : list) {
//            RespCity city = getCity(c.getCityId());
//            if (city != null) {
//                c.setCityName(city.getName());
//            }
            Date signEndTime = c.getSignEndTime();
            Date startTime = c.getStartTime();
            Date endTime = c.getEndTime();
            Integer status = c.getStatus();
            Integer isSettle = c.getIsSettle();
            Integer alreadySignTotalNum = c.getAlreadySignTotalNum();
            Integer limitNum = c.getLimitNum();
            Integer activityStatus = getActivityStatus(signEndTime, startTime,
                    endTime, status, isSettle, alreadySignTotalNum, limitNum);
            c.setStatus(activityStatus);
//            TbSignUserExample signUserExample = new TbSignUserExample();
//            signUserExample.createCriteria()
//                    .andActivityIdEqualTo(c.getActivityId()) //活动id
//                    .andStatusEqualTo((int) Constants.BYTE_ONE);          //有效的
//            List<TbSignUser> signUsers = signUserMapper.selectByExample(signUserExample);
//            int  signUpActivityPeople = signUserMapper.countByExample(signUserExample);
//            for (TbSignUser tbSignUser : signUsers) {
//                TbOrderExample tbOrderExample = new TbOrderExample();
//                tbOrderExample.createCriteria()
//                        .andOrderUidEqualTo(tbSignUser.getOrderUserId()).andActivityIdEqualTo(tbSignUser.getActivityId());
//                List<TbOrder> tbOrders = orderMapper.selectByExample(tbOrderExample);
//                int deductionBirdEggs = 0;
//                int registrationAmount = 0;
//                if(signUpActivityPeople > 0) {
//                    for (int i = 0; i <= signUpActivityPeople - 1; i++) {
////                        deductionBirdEggs += tbOrders.get(i).getAccumulateAmount();
////                        registrationAmount += tbOrders.get(i).getPayAmount().intValue();
//                    }
//                }
//                c.setDeductionBirdEggs(deductionBirdEggs);
//                c.setRegistrationAmount(registrationAmount);
//            }
        }
        return PageObj.create(total, pageNum, pageSize, list);
    }

    //查看活动详情
    @Override
    public ClubActivityDetail getClubActivityDetail(Integer activityId) {
        ClubActivityDetail clubActivityDetail = new ClubActivityDetail();
        ActivityInfo activityInfo = activityOpenService.queryOneActivityById(activityId);
        copyActivityDo(clubActivityDetail, activityInfo);
        ClubActivityDo clubActivityDo = clubActivityAdminMapper.getClubActivityDetail(activityId);
        copyClubActivityDo(clubActivityDetail, clubActivityDo);
        if(activityInfo.getStatus() != 2)
        {
            APIResponse<List<RespClubActivityMember>> list = activityAccountService.getActivityMemberList(activityId, clubActivityDetail.getUserId());
            List<RespClubActivityMember> members = list.getData();
            if (null != members && members.size() > 0) {
                clubActivityDetail.setActivityMembers(members);
            }
        }
        if (null != activityInfo.getPlaceId() && activityInfo.getPlaceId() != 0) {
            try {
                Map<Integer, PlaceDubboProvider> map =
                        placeClient.getPlaceBySinglePlaceId(activityInfo.getPlaceId());
                if (null != map && null != map.get(activityInfo.getPlaceId())) {
                    PlaceDubboProvider placeDubboProvider = new PlaceDubboProvider();
                    if (null != map.get(activityInfo.getPlaceId())) {
                        BeanCopierUtils.copyProperties(map.get(activityInfo.getPlaceId()), placeDubboProvider);
                    }
                    clubActivityDetail.setPlaceDubboProvider(placeDubboProvider);
                    map.clear();
                }
            } catch (RpcException re) {
                throw new BizException("调用场馆失败。");
            }
        }
        clubActivityDetail.setPlaceAddress(activityInfo.getPlaceAddress());
        Integer status = getActivityStatus(activityInfo.getSignEndTime(), activityInfo.getStartTime(),
                activityInfo.getEndTime(), (int) activityInfo.getStatus(),
                clubActivityDetail.getIsSettle(), clubActivityDetail.getAlreadySignTotalNum(),
                clubActivityDetail.getLimitNum());
        clubActivityDetail.setStatus(status);
        return clubActivityDetail;
    }

    /**
     * 获取主报名成员列表
     */
    private List<ClubActivityMember> getActivityMember(Integer activityId) {
        TbSignUserExample tbSignUserExample = new TbSignUserExample();
        tbSignUserExample.createCriteria()
                .andActivityIdEqualTo(activityId).andOrderIdIsNotNull()
                .andStatusEqualTo(1).andIsCancelEqualTo(0);//有效
        tbSignUserExample.setLimit(Limit.buildLimit(1, Integer.MAX_VALUE));
        List<TbSignUser> tbSignUsers = signUserMapper.selectByExample(tbSignUserExample);
        if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbSignUsers)) {
            return null;
        }
        List<ClubActivityMember> memberManages = buildClubActivityMember(tbSignUsers);

        return memberManages;
    }

    private List<ClubActivityMember> buildClubActivityMember(List<TbSignUser> tbSignUsers) {
        List<Byte> orderStatus = new ArrayList<Byte>();
        orderStatus.add(Constants.BYTE_TWO);
        orderStatus.add((byte) 7);
        List<Integer> userIds = Lists.newArrayList();
        for (TbSignUser user : tbSignUsers) {
            if (user.getOrderUserId() != null) {
                userIds.add(user.getOrderUserId());
            }
        }

        //批量查询用户信息
        APIResponse<List<RespUserInfoBase>> respUserInfoBase =
                userServiceFacade.batchQueryUserInfo(userIds);
        if (!respUserInfoBase.isRet()) {
            throw new BizException("调用用户中心系统失败");
        }
        Map<Integer, RespUserInfoBase> userIdAndAvatarMap = Maps.newHashMap();
        List<RespUserInfoBase> respUserInfoBases = respUserInfoBase.getData();
        for (RespUserInfoBase userInfo : respUserInfoBases) {
            if (null != userInfo) {
                userIdAndAvatarMap.put(userInfo.getUid(), userInfo);
            }
        }

        List<ClubActivityMember> retList = Lists.newArrayList();

        for (TbSignUser user : tbSignUsers) {
            ClubActivityMember mainMember = new ClubActivityMember();
            if (user.getIsReplace().intValue() == 1
                    || user.getOrderId() == null) {
                continue;//补报名人没有订单
            }
            TbOrderExample orderExample = new TbOrderExample();

            orderExample.createCriteria().andIdEqualTo(user.getOrderId())
                    .andIsDeleteEqualTo(Constants.BYTE_ZERO).andOrderStatusIn(orderStatus);
            List<TbOrder> orders = orderMapper.selectByExample(orderExample);
            if (null == orders || orders.size() == 0) {
                continue;
            }
            mainMember.setName(user.getName());
            mainMember.setGender(user.getGender());
            mainMember.setUid(user.getOrderUserId());
            mainMember.setMobile(userIdAndAvatarMap.get(user.getOrderUserId()).getMobile());
            retList.add(mainMember);
        }
        return retList;
    }


    //编辑活动
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateClubActivityDetail(ClubActivityDetail clubActivityDetail) {
        if (CollectionUtils.isEmpty(clubActivityDetail.getActivityMediaList())) {
            return false;
        }
        ActivityInfo activityInfo = new ActivityInfo();
        copyToActivityDo(clubActivityDetail, activityInfo);
        if (activityInfo.getId() == null) {
            return false;
        }
        activityOpenService.updateActivity(activityInfo);

        ClubActivityDo clubActivityDo = new ClubActivityDo();
        copyToClubActivityDo(clubActivityDetail, clubActivityDo);
        clubActivityAdminMapper.updateClubActivityDetail(clubActivityDo);
        return true;
    }

    //查看被删除的活动
    @Override
    public PageObj<List<ClubActivityList>> queryDeleteActivity(int pageNum, int pageSize) {
        PageObj<List<ActivityInfo>> resp = activityOpenService.queryDeleteActivity(pageNum + 1, pageSize);
        if (null == resp || null == resp.getItems() || resp.getItems().size() == 0) {
            return PageObj.create(0, pageNum, pageSize, null);
        }
        List<ActivityInfo> activityInfos = resp.getItems();
        List<ClubActivityList> result = new ArrayList<ClubActivityList>();
        List<Integer> idList = new ArrayList<Integer>();
        Map<Integer, ActivityInfo> activityInfoMap = new HashMap<Integer, ActivityInfo>();
        for (ActivityInfo activityInfo : activityInfos) {
            activityInfoMap.put(activityInfo.getId(), activityInfo);
            idList.add(activityInfo.getId());
        }
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdIn(idList).andIsDeleteEqualTo((byte) 1);
        List<TbClubActivity> tbClubActivities = tbClubActivityMapper.selectByExample(example);
        for (TbClubActivity tbClubActivity : tbClubActivities) {
            ActivityInfo activityInfo = activityInfoMap.get(tbClubActivity.getActivityId());
            if (null != activityInfo) {
                ClubActivityList clubActivityList =
                        copyClubActivityList(activityInfo, tbClubActivity);
                result.add(clubActivityList);
            }
        }
        return PageObj.create(resp.getTotal(), pageNum, pageSize, result);
    }

    //查看推荐的活动
    @Override
    public PageObj<List<ClubActivityList>> queryRecommendList(Integer pageNum, Integer pageSize) {
        TbClubActivityExample example = new TbClubActivityExample();
        TbClubActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(ClubConstants.IS_DELETE_FALSE);
        criteria.andIsRecommendEqualTo(ClubConstants.IS_RECOMMEND_TRUE);
        Integer total = tbClubActivityMapper.countByExample(example);
        example.setOrderByClause("create_time desc");
        example.setLimit(Limit.buildLimit(pageNum + 1, pageSize));
        List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(example);
        List<ClubActivityList> result = new ArrayList<ClubActivityList>();
        if (null == clubActivities || clubActivities.size() == 0) {
            return null;
        }
        //有推荐的活动
        for (TbClubActivity tbClubActivity : clubActivities) {
            Integer activityId = tbClubActivity.getActivityId();
            if (null == activityId) {
                return null;
            }
            ActivityInfo activityInfo = activityOpenService.selectOneActivityById(activityId);

            ClubActivityList clubActivityList = copyClubActivityList(activityInfo, tbClubActivity);
            result.add(clubActivityList);
        }
        return PageObj.create(total, pageNum, pageSize, result);
    }

    //更新是否推荐活动 isRecommend 0不推荐，1推荐
    @Override
    public int updateRecommend(Integer activityId, Integer isRecommend) {
        return clubActivityAdminMapper.updateRecommend(activityId, isRecommend);
    }

    //删除活动
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int deleteActivityByActivityId(Integer activityId) {
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdEqualTo(activityId);
        List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(clubActivities))
        {
            logger.warn("没有活动");
            return 0;
        }
        TbClub club = clubMapper.selectByPrimaryKey(clubActivities.get(0).getClubId());
        APIResponse apiResponse =
                clubActivityService.cancelActivity(activityId, club.getUid(), true,1);
        if(!apiResponse.isRet())
        {
            logger.warn("取消失败:" + apiResponse.getErrmsg());
            return 0;
        }
        return clubActivityAdminMapper.deleteActivityByActivityId(activityId);
    }

    public boolean processRefundOrderActivity(Integer activityId, String reason,
                                              Integer uid, Byte refundType) {
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andActivityIdEqualTo(activityId);
        if (null != uid) {
            orderCriteria.andOrderUidEqualTo(uid);
        }
        orderCriteria.andOrderStatusEqualTo(Constants.BYTE_TWO);//支付成功
        List<TbOrder> orderList = orderMapper.selectByExample(orderExample);

        if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(orderList)) {
            return true;
        }

        try {
            for (TbOrder tbOrder : orderList) {
                logger.warn("订单取消退款，订单号：" + tbOrder.getOrderNo());


                String refundOrderNo = CommonUtils.generateOrderNo(tbOrder.getOrderUid());
                //2、退积分和第三方
                APIRequest apiRequest = setRefundOrderParam(tbOrder, refundOrderNo, reason);//组装退款所需参数
                APIResponse<RefundStatusEnum> enumAPIResponse = orderPayService.refundApply(apiRequest);//调用支付系统退款
                if (enumAPIResponse.isRet()) {//申请退款成功
                    //退款申请记录
                    insertOrderRefund(
                            tbOrder.getPayAmount(),
                            tbOrder.getId(),
                            tbOrder.getPayType(),
                            tbOrder.getOrderUid(),
                            reason, refundType,
                            refundOrderNo);
                    //修改订单状态//1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价
                    //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消
                    tbOrder.setOrderStatus((byte) 4);
                    tbOrder.setCancelType((byte) 2);
                    orderMapper.updateByPrimaryKeySelective(tbOrder);
                }
            }
            return true;
        } catch (Exception e) {
            logger.warn("退款申请失败，活动编号：" + activityId);
            return false;
        }
    }

    private boolean refundClubMember(TbOrder tbOrder) {
        Integer uid = tbOrder.getOrderUid();
        Integer activityId = tbOrder.getActivityId();
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria()
                .andUidEqualTo(uid)
                .andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubActivity> list = tbClubActivityMapper.selectByExample(clubActivityExample);
        TbClubActivity clubActivity = null;
        if (null == list || list.size() > 0) {
            return false;
        }
        clubActivity = list.get(0);
        Integer clubId = clubActivity.getClubId();
        Integer payChannel = (int) tbOrder.getPayType();
        String remark = "活动取消退抵扣的俱乐部余额";
        BigDecimal money = tbOrder.getBalanceAmount();
        BigDecimal preAmount = null;
        //获取之前的余额总金额
        TbClubOnlineMemberAccount onlineAccount = this.clubFinanceMgmService.getClubMemberOnlineAccount(clubId, uid);
        if (null != onlineAccount) {

            preAmount = onlineAccount.getMoneyTotal();
        }
        //生成流水
        this.insertClubOnlineMemberAccountStream(uid, activityId, clubId,
                0, money, payChannel, remark, 2, preAmount, preAmount.add(money),
                0, "百灵鸟", "俱乐部用户ID" + uid, "在线退俱乐部抵扣余额");
        //退款到账户
        if (tbOrder.getBalanceAmount() != null &&
                tbOrder.getBalanceAmount().doubleValue() > 0) {//余额抵扣不为0
            int count = refundClubOnlineMemberAccount(tbOrder);
            if (count <= 0) {
                logger.warn("取消活动退款失败，订单号：" + tbOrder.getOrderNo() +
                        "，退回余额抵扣部分失败，金额：" + tbOrder.getBalanceAmount());
                return false;
            }
            logger.warn("取消活动退回余额抵扣部分成功，订单号：" + tbOrder.getOrderNo() +
                    "，金额：" + tbOrder.getBalanceAmount());
        }
        return true;
    }

    public int refundClubOnlineMemberAccount(TbOrder tbOrder) {
        TbClubOnlineMemberAccountExample memberAccountExample = new TbClubOnlineMemberAccountExample();
        TbClubOnlineMemberAccountExample.Criteria memberAccountCriteria = memberAccountExample.createCriteria();
        memberAccountCriteria.andUidEqualTo(tbOrder.getOrderUid());
        memberAccountCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubOnlineMemberAccount> tbClubOnlineMemberAccountList = clubOnlineMemberAccountMapper.selectByExample(memberAccountExample);
        if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(tbClubOnlineMemberAccountList)) {
            TbClubOnlineMemberAccount tbClubOnlineMemberAccount = tbClubOnlineMemberAccountList.get(0);
            BigDecimal moneyTotal = tbClubOnlineMemberAccount.getMoneyTotal();
            tbClubOnlineMemberAccount.setMoneyTotal(moneyTotal.add(tbOrder.getBalanceAmount()));
            int count = clubOnlineMemberAccountMapper.updateByPrimaryKeySelective(tbClubOnlineMemberAccount);
            return count;
        }
        return 0;
    }

    /**
     * 插入俱乐部成员线上账户流水
     */
    private TbClubOnlineMemberAccountStream insertClubOnlineMemberAccountStream(
            int uid,
            int productId,
            int clubId,
            int status,
            BigDecimal income,
            int payChannel,
            String remark,
            int type,
            BigDecimal preAmount,
            BigDecimal sufAmount,
            int clubOnlineMemberAccountId,
            String cheques,
            String drawee,
            String typeIntro) {

        TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = new TbClubOnlineMemberAccountStream();
        clubOnlineMemberAccountStream.setPreAmount(preAmount);
        clubOnlineMemberAccountStream.setSufAmount(sufAmount);
        clubOnlineMemberAccountStream.setProductId(productId);
        clubOnlineMemberAccountStream.setClubOnlineMemberAccountId(clubOnlineMemberAccountId);
        clubOnlineMemberAccountStream.setClubId(clubId);
        clubOnlineMemberAccountStream.setIncome(income);
        clubOnlineMemberAccountStream.setPayChannel((byte) payChannel);
        clubOnlineMemberAccountStream.setRemark(remark);
        clubOnlineMemberAccountStream.setSerialNo(NumberGenerator.getNextOrderNo());
        clubOnlineMemberAccountStream.setUid(uid);
        clubOnlineMemberAccountStream.setStatus((byte) status);
        clubOnlineMemberAccountStream.setType((byte) type);
        clubOnlineMemberAccountStream.setTypeIntro(typeIntro);
        //生成订单号
        clubOnlineMemberAccountStream.setOutTradeNo(NumberGenerator.getNextOrderNo());
        //收款方
        clubOnlineMemberAccountStream.setCheques(cheques);
        //付款方
        clubOnlineMemberAccountStream.setDrawee(drawee);

        if (payChannel == 1) {  //支付宝
            clubOnlineMemberAccountStream.setPayMode("支付宝充值");
        } else if (payChannel == 2) {  //微信支付
            clubOnlineMemberAccountStream.setPayMode("微信充值");
        }

        int n = clubOnlineMemberAccountStreamMapper.insertSelective(clubOnlineMemberAccountStream);
        if (n > 0) {
            return clubOnlineMemberAccountStream;
        } else {
            return null;
        }
    }

    /**
     * 组装退款所需参数
     */
    public APIRequest setRefundOrderParam(TbOrder tbOrder,
                                          String refundOrderNo,
                                          String reason) {
        //支付信息 包含积分、第三方支付
        List<ReqRefundPayInfo> payInfoList = new ArrayList<>();
        ReqRefundPayInfo reqRefundAccumulateInfo = new ReqRefundPayInfo();
        reqRefundAccumulateInfo.setPayId(tbOrder.getPayType().intValue());
        reqRefundAccumulateInfo.setRefundAmount(BigDecimal.valueOf(tbOrder.getAccumulateAmount()));
        payInfoList.add(reqRefundAccumulateInfo);
        ReqRefundPayInfo reqRefundPayInfo = new ReqRefundPayInfo();
        reqRefundPayInfo.setPayId(tbOrder.getPayType().intValue());
        reqRefundPayInfo.setRefundAmount(tbOrder.getPayAmount());
        payInfoList.add(reqRefundPayInfo);
        //商品信息
        List<ReqRefundProduct> reqRefundProductList = new ArrayList<>();
        ReqRefundProduct reqRefundProduct = new ReqRefundProduct();
        reqRefundProduct.setProductId(tbOrder.getActivityId() + "");
        reqRefundProductList.add(reqRefundProduct);

        ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
        reqOrderRefund.setOrderNo(tbOrder.getOrderTradeNo());
        reqOrderRefund.setNeedAudit(false);
        reqOrderRefund.setOutTradeNo(tbOrder.getOrderNo());
        reqOrderRefund.setOutTradeRefundNo(refundOrderNo);
        reqOrderRefund.setReason(reason);

        reqOrderRefund.setUid(tbOrder.getOrderUid());
        reqOrderRefund.setSourceBusinessId(Constants.CLUB_ACTIVITY_REFUND_ORDER_BUSINESS_CODE);
        reqOrderRefund.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        reqOrderRefund.setReqRefundPayInfos(payInfoList);
        reqOrderRefund.setRefundProductList(reqRefundProductList);
        APIRequest apiRequest = new APIRequest();
        apiRequest.setData(reqOrderRefund);
        return apiRequest;
    }

    public boolean insertOrderRefund(BigDecimal amount,
                                     Integer orderId,
                                     Byte payId,
                                     Integer uid,
                                     String reason, Byte refundType,
                                     String refundOrderNo) {
        TbOrderRefund tbOrderRefund = new TbOrderRefund();
        tbOrderRefund.setReason(reason);
        tbOrderRefund.setAmount(amount);
        tbOrderRefund.setRefundUid(uid);
        tbOrderRefund.setAudit((byte) 0);
        tbOrderRefund.setOrderId(orderId);
        tbOrderRefund.setPayId(payId);
        tbOrderRefund.setState((byte) 0);
        tbOrderRefund.setAudit((byte) 0);
        tbOrderRefund.setRefundType(refundType);
        tbOrderRefund.setRefundOrderNo(refundOrderNo);
        int count = orderRefundMapper.insertSelective(tbOrderRefund);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    private ClubActivityList copyClubActivityList(ActivityInfo activityInfo, TbClubActivity tbClubActivity) {
        ClubActivityList clubActivityList = new ClubActivityList();
        clubActivityList.setClubActivityId(tbClubActivity.getId());
        clubActivityList.setUserId(tbClubActivity.getUid());
        clubActivityList.setClubId(tbClubActivity.getClubId());
        if (null == tbClubActivity.getClubId()) {
            return null;
        }
        TbClub tbClub = tbClubMapper.selectByPrimaryKey(tbClubActivity.getClubId());
        if (null == tbClub) {
            return null;
        }
        clubActivityList.setClubName(tbClub.getClubName());
        clubActivityList.setActivityId(tbClubActivity.getActivityId());
        clubActivityList.setActivityName(activityInfo.getName());
        clubActivityList.setPlanner(tbClubActivity.getPlanner());
        clubActivityList.setCityId(tbClubActivity.getCityId());
        clubActivityList.setActivityType((int) tbClubActivity.getActivityType());
        clubActivityList.setCategoryId(tbClubActivity.getCategoryId());
        clubActivityList.setCreateTime(tbClubActivity.getCreateTime());
        //状态转换
        Date signEndTime = activityInfo.getSignEndTime();
        Date startTime = activityInfo.getStartTime();
        Date endTime = activityInfo.getEndTime();
        Integer status = (int) activityInfo.getStatus();
        Integer isSettle = (int) tbClubActivity.getIsSettle();
        Integer alreadySignTotalNum = activityInfo.getAlreadySignTotalNum();
        Integer limitNum = activityInfo.getLimitNum();
        Integer activityStatus = getActivityStatus(signEndTime, startTime,
                endTime, status, isSettle, alreadySignTotalNum, limitNum);
        clubActivityList.setStatus(activityStatus);
        return clubActivityList;
    }

    private void copyToActivityDo(ClubActivityDetail clubActivityDetail, ActivityInfo activityInfo) {
        activityInfo.setId(clubActivityDetail.getActivityId());
        activityInfo.setName(clubActivityDetail.getActivityName());

        activityInfo.setSignStartTime(clubActivityDetail.getSignStartTime());
        activityInfo.setSignEndTime(clubActivityDetail.getSignEndTime());
        activityInfo.setStartTime(clubActivityDetail.getStartTime());
        activityInfo.setEndTime(clubActivityDetail.getEndTime());

        activityInfo.setLimitNum(clubActivityDetail.getLimitNum());
        activityInfo.setAlreadySignTotalNum(clubActivityDetail.getAlreadySignTotalNum());
        RespActivityPoster respActivityPoster = new RespActivityPoster();
        respActivityPoster.setId(clubActivityDetail.getPosterPicId());
        activityInfo.setRespActivityPoster(respActivityPoster);
        activityInfo.setPosterPicId(clubActivityDetail.getPosterPicId());
        activityInfo.setActivityMediaList(clubActivityDetail.getActivityMediaList());
        activityInfo.setActivityDesc(clubActivityDetail.getActivityDesc());
    }

    private void copyToClubActivityDo(ClubActivityDetail clubActivityDetail, ClubActivityDo clubActivityDo) {
        clubActivityDo.setPlanner(clubActivityDetail.getPlanner());
        clubActivityDo.setUserId(clubActivityDetail.getUserId());

        clubActivityDo.setClubActivityId(clubActivityDetail.getClubActivityId());
        clubActivityDo.setClubId(clubActivityDetail.getClubId());
        clubActivityDo.setClubName(clubActivityDetail.getClubName());

        clubActivityDo.setActivityType(clubActivityDetail.getActivityType());
        clubActivityDo.setCategoryId(clubActivityDetail.getCategoryId());

        clubActivityDo.setCityId(clubActivityDetail.getCityId());
        clubActivityDo.setCityName(clubActivityDetail.getCityName());

        clubActivityDo.setAaFee(clubActivityDetail.getAaFee());
        clubActivityDo.setFeeType(clubActivityDetail.getFeeType());
        clubActivityDo.setAaTotal(clubActivityDetail.getAaTotal());
        clubActivityDo.setMaleFee(clubActivityDetail.getMaleFee());
        clubActivityDo.setFemaleFee(clubActivityDetail.getFemaleFee());
        clubActivityDo.setFemaleMemberFee(clubActivityDetail.getFemaleMemberFee());
        clubActivityDo.setMaleMemberFee(clubActivityDetail.getMaleMemberFee());

        clubActivityDo.setIsRecommend(clubActivityDetail.getIsRecommend());

        clubActivityDo.setIsSettle(clubActivityDetail.getIsSettle());
    }

    private void copyActivityDo(ClubActivityDetail clubActivityDetail, ActivityInfo activityInfo) {
        clubActivityDetail.setActivityId(activityInfo.getId());
        clubActivityDetail.setActivityName(activityInfo.getName());

        clubActivityDetail.setSignStartTime(activityInfo.getSignStartTime());
        clubActivityDetail.setSignEndTime(activityInfo.getSignEndTime());
        clubActivityDetail.setStartTime(activityInfo.getStartTime());
        clubActivityDetail.setEndTime(activityInfo.getEndTime());

        clubActivityDetail.setLimitNum(activityInfo.getLimitNum());
        clubActivityDetail.setAlreadySignTotalNum(activityInfo.getAlreadySignTotalNum());

        clubActivityDetail.setPosterPicId(activityInfo.getPosterPicId());
        TbActivityPoster poster = tbActivityPosterMapper.selectByPrimaryKey(activityInfo.getPosterPicId());
        if (null != poster) {
            clubActivityDetail.setPosterPicUrl(poster.getUrl());
        }
        clubActivityDetail.setActivityMediaList(activityInfo.getActivityMediaList());
        clubActivityDetail.setActivityDesc(activityInfo.getActivityDesc());

    }

    private void copyClubActivityDo(ClubActivityDetail clubActivityDetail, ClubActivityDo clubActivityDo) {

        clubActivityDetail.setPlanner(clubActivityDo.getPlanner());
        clubActivityDetail.setUserId(clubActivityDo.getUserId());

        clubActivityDetail.setClubActivityId(clubActivityDo.getClubActivityId());
        clubActivityDetail.setClubId(clubActivityDo.getClubId());
        clubActivityDetail.setClubName(clubActivityDo.getClubName());

        clubActivityDetail.setActivityType(clubActivityDo.getActivityType());
        clubActivityDetail.setCategoryId(clubActivityDo.getCategoryId());

        clubActivityDetail.setCityId(clubActivityDo.getCityId());
        clubActivityDetail.setCityName(clubActivityDo.getCityName());

        clubActivityDetail.setAaFee(clubActivityDo.getAaFee());
        clubActivityDetail.setFeeType(clubActivityDo.getFeeType());
        clubActivityDetail.setAaTotal(clubActivityDo.getAaTotal());
        clubActivityDetail.setMaleFee(clubActivityDo.getMaleFee());
        clubActivityDetail.setFemaleFee(clubActivityDo.getFemaleFee());
        clubActivityDetail.setFemaleMemberFee(clubActivityDo.getFemaleMemberFee());
        clubActivityDetail.setMaleMemberFee(clubActivityDo.getMaleMemberFee());

        clubActivityDetail.setIsRecommend(clubActivityDo.getIsRecommend());

        clubActivityDetail.setIsSettle(clubActivityDo.getIsSettle());

    }

    private static Integer getActivityStatus(Date signEndTime, Date startTime, Date endTime,
                                             Integer status, Integer isSettle, Integer alreadySignTotalNum,
                                             Integer limitNum) {
        Date curTime = new Date();
        //已取消
        if (null != status && status != 0 &&status != 1 &&status != 2 &&status != 3 &&status != 4 &&status != 6) {
            return 5;
        }
        //已结算
        if (null != isSettle && isSettle == 1) {
            return 4;
        }
        //已结束
        if (null != endTime && endTime.getTime() <= curTime.getTime()) {
            return 3;
        }
        //进行中
        if (null != endTime && null != startTime) {
            if (curTime.getTime() < endTime.getTime() &&
                    curTime.getTime() >= startTime.getTime()) {
                return 2;
            }
        }
        //截止报名
        if (null != signEndTime && curTime.getTime()>startTime.getTime()) {
            if (curTime.getTime() >= signEndTime.getTime()) {
                return 1;
            } else {
                //已报满
                if (null != limitNum && limitNum != 0) {
                    if (limitNum <= alreadySignTotalNum) {
                        return 6;
                    }
                }
            }
            //未开始
            return 0;
        }
        return null;
    }

    /**
     * 活动订单列表
     */
    @Override
    public APIResponse<PageObj<List<ResActivityOrderVo>>> queryActivityOrderList(
            ReqActivityOrderQuery reqActivityOrderQuery) {

        Integer queryOrderStatus = reqActivityOrderQuery.getQueryOrderStatus();
        //queryOrderStatus状态: 1待付款 2已付款 3退款中 4已退款 5待结算 6已结算 7已取消
        //IsSettle状态: 0未结算 1已结算 2现场管理已提交(未结算)
        //orderStatus状态: 0超时未支付 1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价 8已取消
        if (queryOrderStatus != null && queryOrderStatus > 0) {
            switch (queryOrderStatus.intValue()) {
                case 1:
                    reqActivityOrderQuery.setOrderStatus(1);
                    break;
                case 2:
                    reqActivityOrderQuery.setOrderStatus(2);
                    break;
                case 3:
                    reqActivityOrderQuery.setOrderStatus(4);
                    break;
                case 4:
                    reqActivityOrderQuery.setOrderStatus(5);
                    break;
                case 5:
                    reqActivityOrderQuery.setIsSettle(0);
                    break;
                case 6:
                    reqActivityOrderQuery.setIsSettle(1);
                    break;
                case 7:
                    reqActivityOrderQuery.setOrderStatus(8);
                    break;
                default:
                    break;
            }
        }

        List<ResActivityOrderVo> retList = Lists.newArrayList();

        reqActivityOrderQuery.setOffset((reqActivityOrderQuery.getPageNum() - 1)
                * reqActivityOrderQuery.getPageSize());

        List<ResActivityOrderVo> queryResActivityOrderVos =
                clubActivityAdminMapper.queryActivityOrderList(reqActivityOrderQuery);
        buildOrderListRes(retList, queryResActivityOrderVos);

        int totalCount =
                clubActivityAdminMapper.queryActivityOrderListCount(reqActivityOrderQuery);
        PageObj<List<ResActivityOrderVo>> pageObj =
                PageObj.create(totalCount, reqActivityOrderQuery.getPageNum(),
                        reqActivityOrderQuery.getPageSize(), retList);

        return APIResponse.returnSuccess(pageObj);

    }

    private List<ResActivityOrderVo> buildOrderListRes(List<ResActivityOrderVo> retList,
                                                       List<ResActivityOrderVo> resActivityOrderVos) {

        //数据库订单状态: 0超时未支付 1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价 8已取消
        //queryOrderStatus状态: 1待付款 2已付款 3退款中 4已退款 5待结算 6已结算 7已取消
        //showOrderStatus状态: 1待付款 2已付款 3退款中 4已退款 5已完成(待结算、已结算) 7已取消

        for (ResActivityOrderVo resActivityOrderVo : resActivityOrderVos) {
            switch (resActivityOrderVo.getOrderStatus().intValue()) {
                case 0:
                case 8:
                    resActivityOrderVo.setShowOrderStatus(7); //订单已取消
                    break;
                case 1:
                case 3:
                    resActivityOrderVo.setShowOrderStatus(1); //订单待付款
                    break;
                case 2:
                case 7:
                    resActivityOrderVo.setShowOrderStatus(2); //订单已付款
                    break;
                case 4:
                    resActivityOrderVo.setShowOrderStatus(3); //订单退款中
                    break;
                case 5:
                    resActivityOrderVo.setShowOrderStatus(4); //订单已退款
                    break;
                case 6:
                    resActivityOrderVo.setShowOrderStatus(5); //订单已完成
                    break;
                default:
                    continue;
            }
            //结算状态 0未结算 1已结算 2现场管理已提交(未结算)

            //前端展示活动状态: 1待结算 2已结算 3已取消

            //活动状态: 1待结算 2已结算 3已取消
            if(null == resActivityOrderVo.getIsSettle())
            {
                resActivityOrderVo.setIsSettle(0);
            }
            if (resActivityOrderVo.getIsSettle().intValue() == 0) {
                resActivityOrderVo.setActivityStatus(1);
                if (resActivityOrderVo.getShowOrderStatus().intValue() == 2
                        && resActivityOrderVo.getEndTime().getTime() < new Date().getTime()) {
                    resActivityOrderVo.setShowOrderStatus(5);
                }
            } else if (resActivityOrderVo.getIsSettle().intValue() == 1) {
                resActivityOrderVo.setActivityStatus(2);
                if (resActivityOrderVo.getShowOrderStatus().intValue() == 2) {
                    resActivityOrderVo.setShowOrderStatus(5);
                }
            } else if (resActivityOrderVo.getStatus().intValue() == 2) {
                resActivityOrderVo.setActivityStatus(3);
            }

            TbClub club = tbClubMapper.selectByPrimaryKey(resActivityOrderVo.getClubId());
            if (club == null) continue;
            resActivityOrderVo.setClubName(club.getClubName());

            //获取参加活动人员
            TbSignUserExample tbSignUserExample = new TbSignUserExample();
            tbSignUserExample.createCriteria().andActivityIdEqualTo(
                    resActivityOrderVo.getActivityId()).andOrderIdEqualTo(
                    resActivityOrderVo.getOrderId()).andStatusEqualTo(1);
            int signUpCount = signUserMapper.countByExample(tbSignUserExample);
            resActivityOrderVo.setSignUpCount(signUpCount);
            retList.add(resActivityOrderVo);
        }

        for (ResActivityOrderVo resActivityOrderVo : retList) {
            resActivityOrderVo.setOrderStatus(null);
            resActivityOrderVo.setIsSettle(null);
            resActivityOrderVo.setStatus(null);
        }

        return retList;
    }

    private static void getStatus(ClubActivityOrderDetail c,
                                                     ClubActivityDetail ca)
    {
        //数据库订单状态: 0超时未支付 1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价 8已取消
        //queryOrderStatus状态: 1待付款 2已付款 3退款中 4已退款 5待结算 6已结算 7已取消
        //showOrderStatus状态: 1待付款 2已付款 3退款中 4已退款 5已完成(待结算、已结算) 7已取消
        ClubActivityOrderDetail.PayInfo payInfo = c.getPayInfo();
        switch (payInfo.getOrderStatus().intValue()) {
            case 0:
            case 8:
                payInfo.setShowOrderStatus(7); //订单已取消
                break;
            case 1:
            case 3:
                payInfo.setShowOrderStatus(1); //订单待付款
                break;
            case 2:
            case 7:
                payInfo.setShowOrderStatus(2); //订单已付款
                break;
            case 4:
                payInfo.setShowOrderStatus(3); //订单退款中
                break;
            case 5:
                payInfo.setShowOrderStatus(4); //订单已退款
            case 6:
                payInfo.setShowOrderStatus(5); //订单已完成
                break;
        }
        //结算状态 0未结算 1已结算 2现场管理已提交(未结算)

        //前端展示活动状态: 1待结算 2已结算 3已取消

        //状态 已取消5
        ClubActivityOrderDetail.ActivityInfo activityInfo = c.getActivityInfo();
        if (ca.getIsSettle().intValue() == 0) {
            activityInfo.setStatus(1);
            if (payInfo.getShowOrderStatus().intValue() == 2
                    && ca.getEndTime().getTime() < new Date().getTime()) {
                payInfo.setShowOrderStatus(5);
            }
        } else if (ca.getIsSettle().intValue() == 1) {
            activityInfo.setStatus(2);
            if (payInfo.getShowOrderStatus().intValue() == 2) {
                payInfo.setShowOrderStatus(5);
            }
        } else if (ca.getStatus().intValue() == 5) {
            activityInfo.setStatus(3);
        }
    }


    @Override
    public APIResponse<ClubActivityOrderDetail> activityOrderDetail(
            Integer orderId, Integer activityId) {

        if (orderId == null || activityId == null) {
            return APIResponse.returnFail("缺少必要参数");
        }

        ClubActivityDetail clubActivityDetail = getClubActivityDetail(activityId);
        if (clubActivityDetail == null) {
            return APIResponse.returnFail("活动不存在");
        }

        if (Strings.isNullOrEmpty(clubActivityDetail.getClubName())) {
            TbClub tbClub = tbClubMapper.selectByPrimaryKey(clubActivityDetail.getClubId());
            clubActivityDetail.setClubName(tbClub.getClubName());
        }

        TbSignUserExample tbSignUserExample = new TbSignUserExample();
        tbSignUserExample.createCriteria().andActivityIdEqualTo(activityId).
                andOrderIdEqualTo(orderId);
        List<TbSignUser> tbSignUsers = signUserMapper.selectByExample(tbSignUserExample);
        if (CollectionUtils.isEmpty(tbSignUsers)) {
            return APIResponse.returnFail("活动暂无报名人");
        }

        TbOrder tbOrder = orderMapper.selectByPrimaryKey(orderId);
        if (tbOrder == null) {
            return APIResponse.returnFail("订单不存在");
        }
        TbCategory tbCategory = categoryMapperMapper.selectByPrimaryKey(clubActivityDetail.getCategoryId());
        if (tbCategory == null) {
            return APIResponse.returnFail("活动类型不存在");
        }
        ClubActivityOrderDetail clubActivityOrderDetail = new ClubActivityOrderDetail();

        buildActivityBaseInfo(tbOrder, tbSignUsers, clubActivityDetail, clubActivityOrderDetail);
        buildSignUpInfoList(tbSignUsers, clubActivityOrderDetail);
        buildActivityInfo(clubActivityDetail, clubActivityOrderDetail, tbCategory);
        buildPayInfo(tbOrder, clubActivityDetail, clubActivityOrderDetail);
        getStatus(clubActivityOrderDetail, clubActivityDetail);
        return APIResponse.returnSuccess(clubActivityOrderDetail);
    }

    private void buildActivityBaseInfo(
            TbOrder tbOrder,
            List<TbSignUser> tbSignUsers,
            ClubActivityDetail clubActivityDetail,
            ClubActivityOrderDetail clubActivityOrderDetail) {

        TbSignUser mainSignUser = null;
        int manCount = 0;
        int womenCount = 0;
        for (TbSignUser signUser : tbSignUsers) {
            if (signUser.getIsReplace().intValue() != 0) {
                //不是主要信息人
                continue;
            }
            mainSignUser = signUser;
            for (TbSignUser replaceSignUser : tbSignUsers) {
                if (replaceSignUser.getOrderId().intValue()
                        != signUser.getOrderId().intValue()) {
                    continue;
                }
                if (replaceSignUser.getGender().intValue() == 1) {
                    manCount++;
                }
                if (replaceSignUser.getGender().intValue() == 2) {
                    womenCount++;
                }
            }
        }
        ClubActivityOrderDetail.BaseInfo baseInfo = new ClubActivityOrderDetail().new BaseInfo();
        baseInfo.setPlatformType(tbOrder.getPlatformType());
        baseInfo.setOrderType(clubActivityDetail.getFeeType());
        baseInfo.setOrderNo(tbOrder.getOrderNo());
        baseInfo.setMainSignUpName(mainSignUser.getName());
        baseInfo.setMainSignUpMobile(mainSignUser.getMobile());
        baseInfo.setCreateTime(tbOrder.getPayTime());
        boolean isClubMember = clubMemberService.isClubMember(
                tbOrder.getOrderUid(), clubActivityDetail.getClubId());
        baseInfo.setIsClubMember(isClubMember);
        baseInfo.setSignUpNumInfo(manCount + "男" + womenCount + "女");
        clubActivityOrderDetail.setBaseInfo(baseInfo);
    }

    private void buildSignUpInfoList(List<TbSignUser> tbSignUsers,
                                     ClubActivityOrderDetail clubActivityOrderDetail) {
        List<ClubActivityOrderDetail.SignUpInfo> signUpInfoList = Lists.newArrayList();
        for (TbSignUser signUser : tbSignUsers) {
            ClubActivityOrderDetail.SignUpInfo signUpInfo =
                    new ClubActivityOrderDetail().new SignUpInfo();
            signUpInfo.setGender(signUser.getGender());
            signUpInfo.setName(signUser.getName());
            signUpInfo.setMobile(signUser.getIsReplace().intValue() != 0 ? "--" : signUser.getMobile());
            signUpInfoList.add(signUpInfo);
        }
        clubActivityOrderDetail.setSignUpInfoList(signUpInfoList);
    }

    private void buildActivityInfo(ClubActivityDetail clubActivityDetail,
                                   ClubActivityOrderDetail clubActivityOrderDetail, TbCategory category) {
        ClubActivityOrderDetail.ActivityInfo activityInfo
                = new ClubActivityOrderDetail().new ActivityInfo();
        activityInfo.setCityName(clubActivityDetail.getCityName());
        activityInfo.setActivityName(clubActivityDetail.getActivityName());
        activityInfo.setActivityId(clubActivityDetail.getActivityId());
        activityInfo.setCategoryName(category.getName());
        activityInfo.setClubName(clubActivityDetail.getClubName());
        activityInfo.setSignStartTime(clubActivityDetail.getSignStartTime());
        activityInfo.setStatus(clubActivityDetail.getStatus());
        if (clubActivityDetail.getFeeType().intValue() == 0) {//aa活动
            activityInfo.setAaFee(clubActivityDetail.getAaFee());
            activityInfo.setAaTotal(clubActivityDetail.getAaTotal());
        } else if (clubActivityDetail.getFeeType().intValue() == 1) {
            activityInfo.setFemaleFee(clubActivityDetail.getFemaleFee());
            activityInfo.setFemaleMemberFee(clubActivityDetail.getFemaleMemberFee());
            activityInfo.setMaleFee(clubActivityDetail.getMaleFee());
            activityInfo.setMaleMemberFee(clubActivityDetail.getMaleMemberFee());
        }
        clubActivityOrderDetail.setActivityInfo(activityInfo);
    }

    private void buildPayInfo(TbOrder tbOrder,
                              ClubActivityDetail clubActivityDetail,
                              ClubActivityOrderDetail clubActivityOrderDetail) {
        ClubActivityOrderDetail.PayInfo payInfo = new ClubActivityOrderDetail().new PayInfo();
        payInfo.setOrderType(clubActivityDetail.getFeeType());
        payInfo.setOrderAmount(tbOrder.getOrderAmount());
        payInfo.setExchangeRmb(tbOrder.getExchangeRmb());
        payInfo.setBalanceAmount(tbOrder.getBalanceAmount());
        payInfo.setPayAmount(tbOrder.getPayAmount());
        payInfo.setPayType(tbOrder.getPayType());
        payInfo.setPayTime(tbOrder.getPayTime());
        payInfo.setOrderStatus((int) tbOrder.getOrderStatus());
        payInfo.setOrderUid(tbOrder.getOrderUid());

        TbAASettlementRefundDetail settlementRefundDetail =
                clubAccountService.getTbAASettlementRefundDetail(
                        tbOrder.getOrderNo(), tbOrder.getActivityId());

        //0超时未支付 1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价 8已取消
        switch (tbOrder.getOrderStatus().intValue()) {
            case 2:
            case 7:
                payInfo.setOrderTradingStatus(2);
                if (clubActivityDetail.getFeeType().intValue() == 0) {//aa活动
                    if (settlementRefundDetail == null) {
                        payInfo.setOnlineClubBalanceAmountIncome(tbOrder.getBalanceAmount());
                        payInfo.setOnlineClubExchangeRmbIncome(tbOrder.getExchangeRmb());
                        payInfo.setOnlineClubPayAmountIncome(tbOrder.getPayAmount());
                        payInfo.setOnlineClubTotalAmountIncome(tbOrder.getOrderAmount());
                    }
                } else if (clubActivityDetail.getFeeType().intValue() == 1) {
                    payInfo.setOnlineClubBalanceAmountIncome(tbOrder.getBalanceAmount());
                    payInfo.setOnlineClubExchangeRmbIncome(tbOrder.getExchangeRmb());
                    payInfo.setOnlineClubPayAmountIncome(tbOrder.getPayAmount());
                    payInfo.setOnlineClubTotalAmountIncome(tbOrder.getOrderAmount());
                }
                break;
            case 4:
            case 5:
            case 6:
                payInfo.setOrderTradingStatus(1);

                TbOrderRefundExample tbOrderRefundExample = new TbOrderRefundExample();
                tbOrderRefundExample.createCriteria().andOrderIdEqualTo(tbOrder.getId())
                        .andRefundUidEqualTo(tbOrder.getOrderUid());
                List<TbOrderRefund> tbOrderRefunds =
                        orderRefundMapper.selectByExample(tbOrderRefundExample);


                payInfo.setRefundOrderAmount(tbOrder.getOrderAmount());
                payInfo.setRefundBalanceAmount(tbOrder.getBalanceAmount());
                payInfo.setRefundExchangeRmb(tbOrder.getExchangeRmb());
                payInfo.setRefundPayAmount(tbOrder.getPayAmount());
                if (CollectionUtils.isNotEmpty(tbOrderRefunds)) {
                    payInfo.setRefundTime(tbOrderRefunds.get(0).getCreateTime());
                } else {
                    payInfo.setRefundTime(tbOrder.getUpdateTime());
                }
                payInfo.setOnlineClubBalanceAmountIncome(new BigDecimal(0));
                payInfo.setOnlineClubExchangeRmbIncome(new BigDecimal(0));
                payInfo.setOnlineClubPayAmountIncome(new BigDecimal(0));
                payInfo.setOnlineClubTotalAmountIncome(new BigDecimal(0));

                if (clubActivityDetail.getFeeType().intValue() == 0) {//aa活动

                    if (settlementRefundDetail != null) {
                        BigDecimal accumulateFee = new BigDecimal(
                                settlementRefundDetail.getRefundAccumulateAmount())
                                .multiply(new BigDecimal(0.1));//暂时写死鸟蛋兑换比例
                        accumulateFee = accumulateFee.setScale(1, RoundingMode.DOWN);

                        BigDecimal refundOrderAmount = settlementRefundDetail.getRefundBalanceAmount()
                                .add(settlementRefundDetail.getRefundThirdPartyAmount())
                                .add(accumulateFee);

                        payInfo.setRefundOrderAmount(refundOrderAmount);
                        payInfo.setRefundBalanceAmount(settlementRefundDetail.getRefundBalanceAmount());
                        payInfo.setRefundExchangeRmb(accumulateFee);
                        payInfo.setRefundPayAmount(settlementRefundDetail.getRefundThirdPartyAmount());
                        payInfo.setRefundWay("AA结算");
                        payInfo.setRefundTime(settlementRefundDetail.getRefundTime());

                        payInfo.setOnlineClubBalanceAmountIncome(tbOrder.getBalanceAmount()
                                .subtract(settlementRefundDetail.getRefundBalanceAmount()));
                        payInfo.setOnlineClubExchangeRmbIncome(
                                tbOrder.getExchangeRmb().subtract(accumulateFee));
                        payInfo.setOnlineClubPayAmountIncome(tbOrder.getPayAmount()
                                .subtract(settlementRefundDetail.getRefundThirdPartyAmount()));
                        payInfo.setOnlineClubTotalAmountIncome(
                                tbOrder.getOrderAmount().subtract(refundOrderAmount));
                    }

                } else if (clubActivityDetail.getFeeType().intValue() == 1) {
                    payInfo.setRefundWay("原路返还");
                }
                break;
            default:
                break;
        }

        clubActivityOrderDetail.setPayInfo(payInfo);
    }
    private Date getStartQueryTime(Date startQueryTime){

        if (startQueryTime != null){
            try {
                return sf.parse(sf.format(startQueryTime));
            } catch (ParseException e) {
                return null;
            }
        }
        return startQueryTime;
    }

    private Date getEndQueryTime(Date startQueryTime, Date endQueryTime){
        if (endQueryTime != null){
            endQueryTime = getStartQueryTime(endQueryTime);

            Calendar cal = Calendar.getInstance();
            cal.setTime(endQueryTime);
            cal.add(Calendar.HOUR_OF_DAY, 24);
            endQueryTime = cal.getTime();
        }
        return endQueryTime;
    }
}
